<!-- 大轮播图 -->
<template>
	<el-upload
					:action="constant.uploadUrl"
					:headers="{ Authorization: cache.getToken() }"
					:before-upload="beforeUpload"
					:on-success="handleSuccess"
					:show-file-list="false"
                    accept="video/*, image/*"
                    style="margin-bottom: 10px;"
				>
					<el-button v-auth="'sys:attachment:save'" icon="Plus" type="primary">上传</el-button>
        

				</el-upload>
  
 <el-table :data="data.tableData" row-key="id" table-layout="auto" style="width: 100%"  @selection-change="handleSelectionChange">
    <!-- <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column> -->
			<el-table-column prop="name" label="附件名称" header-align="center" align="center" width="300"></el-table-column>
			<el-table-column label="附件地址" header-align="center" align="center" width="300">
				<template #default="scope">
				<el-button type="text" @click="showAttachment(scope.row.url)">查看</el-button>
				</template>
			</el-table-column> 
			<!-- <el-table-column prop="url" label="附件地址" header-align="center" align="center" width="300"></el-table-column> -->
			<el-table-column prop="createdByName" label="创建人名字	" header-align="center" align="center" width="200"></el-table-column>
            <el-table-column prop="creator" label="创建者" header-align="center" align="center" width="200"></el-table-column>
			<el-table-column prop="size" label="附件大小" header-align="center" align="center" width="200"></el-table-column>
		    <el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
     <template #default="scope">
       <el-button type="danger" @click="deleteBatchHandle(scope.row.id)">删除</el-button>
     </template>
   </el-table-column>
 </el-table>

	<el-dialog
    v-model="dialogVisible"
    title="附件预览"
    width="900"
    :before-close="handleClose"
  >

    <div v-if="attachmentType === 'image'">
        <img :src="currentAttachmentUrl" alt="附件预览" style="    width: 700px;    margin: 0 6rem; height: auto;" />
      </div>
      <div v-else-if="attachmentType === 'video'">
        <video :src="currentAttachmentUrl" controls style="max-width: 100%; height: auto;"></video>
      </div>
      <div v-else>
        <p>不支持的文件类型。</p>
      </div>

  </el-dialog>

 <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getList" @current-change="getList" style="margin-top: 20px;display:flex;justify-content: flex-end;" />
 <CarouselFrom ref="dialogFormRef" @resetList="getList"></CarouselFrom>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { listLink, editLink, deleteLink ,carouselList,carouseldelete} from '@/api/allApi'
import CarouselFrom  from './CarouselFrom.vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import constant from '@/utils/constant'
import { IHooksOptions } from '@/hooks/interface'
import cache from '@/utils/cache'
import { convertSizeFormat } from '@/utils/tool'
import type { UploadProps } from 'element-plus'
import { carouselLunBigs } from '@/api/sys/attachment'
import { useCrud } from '@/hooks'
import service from '@/utils/request'
import { el } from 'element-plus/es/locale'


// let tableData = reactive([])
const pageNum = ref(1) //第几页
const pageSize = ref(10) //每页多少条
const total = ref(0) //总条数



const dialogVisible = ref(false)
const currentAttachmentUrl = ref('')
const attachmentType = ref('')

    // 复选框
    const selectedRows = ref([]);
    // 选中行
        const addnum = ref(0); 

	//   获取页面有多少条数据
	const addpagenum = ref("")
	const data = reactive({
	tableData: []
	})

	onMounted(() => {
	getList()
	})

    // 处理选中行的变化
        const handleSelectionChange = (val: { map: (arg0: (item: any) => any) => never[] }) => {
          selectedRows.value = val.map((item: { id: any }) => item.id); // 存储选中的行的id
          console.log( selectedRows.value,'存储选中的行的id')
        };

		
	 const showAttachment = (url: string) => {

      attachmentType.value = getFileTypeFromUrl(url);
      currentAttachmentUrl.value = url;
      dialogVisible.value = true;

	  console.log(  currentAttachmentUrl.value)
    };
 
    const getFileTypeFromUrl = (url: string): string => {
      const ext = url.split('.').pop()?.toLowerCase() ?? '';
      if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext)) {
        return 'image';
      } else if (['mp4', 'webm', 'ogg'].includes(ext)) {
        return 'video';
      } else {
        return 'unsupported';
      }
    };
 
    const handleClose = () => {
      dialogVisible.value = false;
      currentAttachmentUrl.value = '';
      attachmentType.value = '';
    };

// 初始化  获取数据
const getList = () => {
 carouselList({
       websiteId: Number(localStorage.getItem('WebsiteId')), //网站id 1：鞍钢官网 2：博物馆
       page: pageNum.value,
       size: pageSize.value
   }).then((res: any) => {
     data.tableData = res.data.list   
   
   })
}

const dialogFormRef = ref()

const state: IHooksOptions = reactive({
	deleteUrl: '/carousel/delete',
})


const queryRef = ref()
const dataForm = reactive({
	name: '',
	size: '',
	url: '',
    tenantId: '',
    websiteId: 1
})

const handleSuccess: UploadProps['onSuccess'] = (res, file) => {
    
  console.log(  dataForm.tenantId,'  dataForm.tenantId')
	if (res.code !== 0) {
		ElMessage.error('上传失败：' + res.msg)
		return false
	}

	Object.assign(dataForm, res.data)
  dataForm.tenantId= JSON.parse(localStorage.getItem('userInfo')).id, //租户id
  dataForm.websiteId= Number(localStorage.getItem('WebsiteId')), //网站id

  console.log(  dataForm.tenantId,'  dataForm.tenantId')

  carouselLunBigs(dataForm).then(() => {
		ElMessage.success({
			message: '上传成功',
			duration: 500,
			onClose: () => {
				getList()
			}
		})
	})
}

const beforeUpload: UploadProps['beforeUpload'] = file => {
	if (file.size / 1024 / 1024 / 100 > 1) {
		ElMessage.error('文件大小不能超过100M')
		return false
	}
	return true
}

const { deleteBatchHandle} = useCrud(state)

</script>

<style lang="scss" scoped>
//搭配el-table里的table-layout="auto"属性，再让每一列里的width为空即可展现出适应表格内容的列宽
:deep(.el-table .cell) {
   width: max-content;
   display: inline-block;
}
</style>
